<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>在线聊天室</title>
</head>
<body>
<!--    输入内容-->
    <input type="text" placeholder="输入你的内容" />
<!--    发送请求-->
    <button>发送请求</button>
<!--    显示结果-->
    <div></div>
    <script>
        var input = document.querySelector("input")
        var button = document.querySelector("button")
        var div = document.querySelector("div")
        //该参数为Websocket服务地址
        var socket = new WebSocket("ws://echo.websocket.org")

        socket.addEventListener('open',function(){
            div.innerHTML = "连接服务成功"
        })
        //主动的给Websocket服务发送消息
        button.addEventListener('click', function (){
            var value = input.value
            socket.send(value)
        })

        //接收Websocket服务的数据
        socket.addEventListener('message',function (e){
            console.log(e.data)
            div.innerHTML = e.data
        })
        socket.addEventListener('close',function (){
            div.innerHTML = '服务断开连接'
        })
    </script>
</body>
</html>